package com.test.controller;

import com.jpay.ext.kit.PaymentKit;
import com.test.okhttp.OkHttpUtils;
import com.test.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/OkhttpController")
public class OkhttpController {

    @Autowired
    private OkHttpUtils okHttpUtils;

    @GetMapping("/test")
    public String test() {
        String nonceStr = UUID.randomUUID().toString().replace("-","");
        String outTradeNo = "534742724272853269";
        String outFrfundNo = "534742724272853270";
        String totalFee = "1";
        String refundFee = "1";
        String notifyUrl = "https://bbjk.quickhealmall.com/api/wechat/pcdRefundCallback";
        Map<String, String> map = this.refundMoney(nonceStr, outTradeNo, outFrfundNo, totalFee, refundFee, notifyUrl);
        return JsonUtil.toJson(map);
    }

    public Map<String, String> refundMoney(String nonceStr, String outTradeNo, String outFrfundNo, String totalFee,
                                           String refundFee, String notifyUrl) {
        String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";

        Map<String, String> inParameters = new HashMap<String, String>();
        inParameters.put("appid", "wx7285e3370cebf1f5");
        inParameters.put("mch_id", "1511682811");
        inParameters.put("nonce_str", nonceStr);
        inParameters.put("out_trade_no", outTradeNo);
        inParameters.put("out_refund_no", outFrfundNo);
        inParameters.put("total_fee", totalFee);
        inParameters.put("refund_fee", refundFee);
        inParameters.put("notify_url", notifyUrl);
        inParameters.put("sign", PaymentKit.createSign(inParameters, "pfksapimy66787687665265645821156"));
        if(log.isDebugEnabled()) {
            log.debug("微信支付退款参数：" + inParameters.toString());
        }
        try {
            String resultXml = okHttpUtils.syncPostJson(url, PaymentKit.toXml(inParameters));
            Map<String, String> map = PaymentKit.xmlToMap(resultXml);
            if(log.isDebugEnabled()) {
                log.debug("微信支付退款返回结果：" + map.toString());
            }
            if(map.get("return_code").equals("FAIL")) {
                log.info(JsonUtil.toJson(map));
            }
            return map;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
